using Dapper;
using Finance.Api.Read.Applications.Commands.库存调拨;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;

namespace Finance.Api.Read.Applications.CommandHands.库存调拨
{
    public class DeploymentQueryCommandHandlers : IRequestHandler<DeploymentQueryCommand, ApiResult<ApiPaging<List<DeploymentDto>>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<DeploymentQueryCommandHandlers> _logger;

        public DeploymentQueryCommandHandlers(IDapperDb db, ILogger<DeploymentQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<List<DeploymentDto>>>> Handle(DeploymentQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<List<DeploymentDto>>>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder totalNum = new StringBuilder();

            ApiPaging<List<DeploymentDto>> res = new ApiPaging<List<DeploymentDto>>();
            var parameters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT 
                            a.Id,
                            a.Deployment,
                            a.Time,
                            a.DeploymentStyle,
                            a.DeploymentInto,
                            a.DeploymentOut,
                            a.Message,
                            a.CreateName,
                            a.CreateTime,
                            a.UpdateName,
                            a.UpdateTime,
                            a.DeleteName,
                            a.DeleteTime,
                            SUM(d.DeploymentNum) as TotalDeploymentNum,
                            GROUP_CONCAT(d.ProductName SEPARATOR '、') as ProductNames
                    FROM DeploymentModel a
                    LEFT JOIN DeploymentDetail d ON a.Id = d.Deploymentid
                    WHERE a.IsDelete=0 ");

                // 构建总数查询SQL
                totalNum.Append(@"SELECT COUNT(1)
                            FROM DeploymentModel a
                            WHERE a.IsDelete=0 ");

                // 添加查询条件
                if (!string.IsNullOrEmpty(request.Deployment))
                {
                    stringBuilder.Append(" AND a.Deployment LIKE @Deployment");
                    totalNum.Append(" AND a.Deployment LIKE @Deployment");
                    parameters.Add("@Deployment", $"%{request.Deployment}%");
                }

                if (!string.IsNullOrEmpty(request.DeploymentStyle))
                {
                    stringBuilder.Append(" AND a.DeploymentStyle = @DeploymentStyle");
                    totalNum.Append(" AND a.DeploymentStyle = @DeploymentStyle");
                    parameters.Add("@DeploymentStyle", request.DeploymentStyle);
                }

                if (!string.IsNullOrEmpty(request.DeploymentInto))
                {
                    stringBuilder.Append(" AND a.DeploymentInto LIKE @DeploymentInto");
                    totalNum.Append(" AND a.DeploymentInto LIKE @DeploymentInto");
                    parameters.Add("@DeploymentInto", $"%{request.DeploymentInto}%");
                }

                if (!string.IsNullOrEmpty(request.DeploymentOut))
                {
                    stringBuilder.Append(" AND a.DeploymentOut LIKE @DeploymentOut");
                    totalNum.Append(" AND a.DeploymentOut LIKE @DeploymentOut");
                    parameters.Add("@DeploymentOut", $"%{request.DeploymentOut}%");
                }

                if (request.StartTime.HasValue)
                {
                    stringBuilder.Append(" AND a.Time >= @StartTime");
                    totalNum.Append(" AND a.Time >= @StartTime");
                    parameters.Add("@StartTime", request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    stringBuilder.Append(" AND a.Time <= @EndTime");
                    totalNum.Append(" AND a.Time <= @EndTime");
                    parameters.Add("@EndTime", request.EndTime.Value);
                }

                if (!string.IsNullOrEmpty(request.CreateName))
                {
                    stringBuilder.Append(" AND a.CreateName LIKE @CreateName");
                    totalNum.Append(" AND a.CreateName LIKE @CreateName");
                    parameters.Add("@CreateName", $"%{request.CreateName}%");
                }

                // 执行总数查询
                int totalCount = await _db.QueryFirst<int>(totalNum.ToString(), parameters);

                // 添加分组和排序
                stringBuilder.Append(" GROUP BY a.Id ORDER BY a.Id DESC");

                // 添加分页
                stringBuilder.Append($" LIMIT {((request.index - 1) * request.size)}, {request.size}");

                // 执行数据查询
                var list = await _db.Query<DeploymentDto>(stringBuilder.ToString(), parameters);
                
                res.data = list.ToList();
                res.totalcount = totalCount;
                res.totalpcount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
                result.data = res;
                result.message = "库存调拨分页查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("库存调拨分页查询失败: {Message}", ex.Message);
                result.message = "库存调拨分页查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 